// pages/punch/punch.js
//获取应用实例
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js')  //引入获得地址的js文件
var qqmapsdk;
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 地理定位
    latitude: null,//地理定位
    longitude: null,
    address: null,
    city: "",//定位城市
    islogin:false,//是否登录
    msg:'',//打卡成功文本
    ranking:'',
    punchDays:'',
    punchNum: '',
    currentData: 0,//tab标签切换
    selectPerson: true,//tab标签切换
    countryRanking:[],// tab切换数据(全国)
    cityRanking:[],// tab切换数据(省市)
    // 底部我的数据
    countryKingnum:0,//全国步数排名
    cityKingnum:0,//全市步数排名
    mystep:0,//我的步数
    // 日历数据
    showtime: false,//是否显示日历
    // 日期
    dateNum: "",
    year: 0,
    month: 0,
    week: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],//日历
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    ordertime: "",
    value: 1,
    signIn: []//已签到的日期
  },
  //获取当前滑块的index
  bindchange: function (e) {
    const that = this;
    that.setData({
      currentData: e.detail.current
    })
  },
  //点击切换，滑块index赋值
  checkCurrent: function (e) {
    const that = this;

    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {

      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },
  // 已登录，打卡
  punch(){
    let that=this
    let host=app.globalData.host
    wx.request({
      url: host+'/H5/Clock/clock_in',
      method:'post',
      data:{
        openid:app.globalData.openid,
        step:app.globalData.step
      },
      success(res){
        // console.log(res)
        if(res.data.code==="200"){
          that.setData({
            msg:'今日已打卡'
          })
        }
      },
      fail(res){
        console.log(res)
      }
    })
  },
  // 未登录，跳转到注册页
  partActivity(){
    // console.log(222);
    wx.navigateTo({
      url: '/pages/index/index'
    })
  },
  // 获取全国前十排行
  getranking(){
    let that=this
    let host = app.globalData.host
    wx.request({
      url: host+'/H5/Clock/nationalRank',
      success(res) {
        // console.log(res.data.data)
        if(res.data.code==="200"){
          that.setData({
            countryRanking:res.data.data
          })
        }
      },
      fail(res){
        console.log(res);
      }
    })
  },
  // 获取省市排行
  getcitysranking(){
    let that = this
    let host = app.globalData.host
    wx.request({
      url: host +'/H5/Clock/cityRank',
      success(res){
        // console.log(res.data.data);
        if(res.data.code==="200"){
          that.setData({
            cityRanking:res.data.data
          })
        }
      },
      fail(res){
        console.log(res);
      }
    })
  },
  // 获取顶部省排行数据
  getproranking(){
    let that=this
    let host=app.globalData.host
    let openid=app.globalData.openid
    // console.log(openid);
    wx.request({
      url: host +'/H5/Clock/topRank',
      data:{
        openid:openid
      },
      success(res){
        // console.log(res.data);
        that.setData({
          islogin:true,
          ranking: res.data.data.my_province_rank,
          punchDays: res.data.data.consecutive_days,
          punchNum: res.data.data.total_clock_in
        })
      },
      fail(res){
        console.log(res);
      }
    })
  },
  getmyranking(){
    let that=this
    let host=app.globalData.host
    wx.request({
      url: host +'/H5/Clock/bottom_Rank',
      data:{
        openid:app.globalData.openid
      },
      success(res){
        // console.log(res);
        if(res.data.code==="200"){
          that.setData({
            countryKingnum: res.data.data.nationalRank,//全国步数排名
            cityKingnum: res.data.data.cityRank,//全市步数排名
            mystep: res.data.data.mySteps,//我的步数
          })
        }
      },
      fail(res){
        console.log(res);
      }
    })
  },
  // 日历显示内容
  dateInit(setYear, setMonth) {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let dateArr = [];//需要遍历的日历数组数据
    let seatsDate = [];
    let arrLen = 0;//dateArr的数组长度
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth();//没有+1方便后面计算当月总天数
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + ',' + (month + 1) + ',' + 1).getDay();//目标月1号对应的星期
    let dayNums = new Date(year, nextMonth, 0).getDate();//获取目标月有多少天
    let obj = {};
    let num = 0;
    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    arrLen = startWeek + dayNums;
    let arrsign=[]
    let sing=[]
    for(let n=0;n<this.data.signIn.length;n++){
      sing=this.data.signIn[n].split('-');
      if(sing[1]==(month+1)){
        sing = this.data.signIn[n];
        arrsign.push(sing)
      }
    }
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        let newNum = num < 10 ? '0' + num : num;
        let newMonth = month < 10 ? '0' + month : month;
        obj = {
          isToday: '' + year + '-' + (newMonth + 1) + '-' + newNum,
          dateNum: num,
          signIn:arrsign[i]
        }
      } else {
        obj = {};
      }
      if (Object.keys(obj).length == 0){
        arrsign.splice(i, 0, ' ');
      }else if (obj.signIn !== undefined) {
        let s = obj.signIn.split('-');
        let ss = obj.isToday.split('-');
        let o = s[2] - ss[2];
        if (o !== 0) {
          arrsign.splice(i, 0, ' ');
        }
      }
      dateArr[i] = obj;
    }
    this.setData({
      dateArr: dateArr
    })
    // console.log(dateArr);
    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
    if (nowYear == getYear && nowMonth == getMonth) {
      this.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      })
    } else {
      this.setData({
        isTodayWeek: false,
        todayIndex: -1
      })
    }
  },
  /**
   * 上月切换
   */
  lastMonth: function () {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
    this.setData({
      year: year,
      month: (month + 1)
    })
    this.dateInit(year, month);
  },
  /**
   * 下月切换
   */
  nextMonth: function () {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
    let month = this.data.month > 11 ? 0 : this.data.month;
    this.setData({
      year: year,
      month: (month + 1)
    })
    this.dateInit(year, month);
  },
  //获取打卡记录
  getpunch() {
    let that = this
    let host = app.globalData.host
    wx.request({
      url: host + '/H5/Clock/clock_in',
      data: {
        startTime: that.dateArr[0].isToday,
        endTime: that.dateArr[dateArr.length - 1].isToday + ' 24:00:00'
      },
      success(res) {
        console.log(res);
      },
      fail(res) {
        cosnole.log(res);
      }
    })
  },
  // 获取位置
  getLocation() {
    var that = this
    wx.getLocation({//调用API得到经纬度
      type: 'wgs84',
      success: function (res) {
        var speed = res.speed
        var accuracy = res.accuracy
        var latitude = res.latitude
        var longitude = res.longitude

        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        //地址解析
        var demo = new QQMapWX({
          key: '6FGBZ-6HEWU-WZ6V7-2UOBS-L7ZAV-PZBA5'// 这个KEY的获取方式在上面链接 腾讯位置服务的开发文档中有详细的申请密钥步骤
        });
        demo.reverseGeocoder({//地址解析
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            // console.log(res.result.address_component);
            that.setData({
              city: res.result.address_component.city
            })
            // console.log(that.data.province);
            // console.log(res.result.address_component.district);
            //获得地址
            that.setData({
              address: res.result.address
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            // console.log(res);
          }
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getranking()//获取全国排行
    this.getcitysranking()//获取省市排行
    this.getproranking()//获取顶部排行
    this.getmyranking()//获取我的排行
    // this.getpunch()//获取打卡记录
    this.getLocation()//一进来就得到地址
    // 日历部分加载
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    this.dateInit();
    this.setData({
      year: year,
      month: month,
      isToday: '' + year + month + now.getDate()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})